package com.yhn.init.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.util.SaResult;
import com.yhn.init.common.BaseResponse;
import com.yhn.init.common.ErrorCode;
import com.yhn.init.common.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

/**
 * 全局异常处理器
 *
 * @author yhnyhn123
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler(NotLoginException.class)
    public BaseResponse<?> loginExceptionHandler(NotLoginException e) {
        log.error("RuntimeException", e);
        return ResultUtils.error(ErrorCode.NO_LOGIN_ERROR, "用户未登录");
    }

    @ExceptionHandler(NotPermissionException.class)
    public BaseResponse<?> permissionExceptionHandler(NotPermissionException e) {
        log.error("RuntimeException", e);
        return ResultUtils.error(ErrorCode.NO_PERMISSION_ERROR);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse<?> handleValidationExceptions(MethodArgumentNotValidException ex) {
        return ResultUtils.error(ErrorCode.PARAMS_ERROR, Objects.requireNonNull(ex.getBindingResult().getFieldError()).getDefaultMessage());
    }

    @ExceptionHandler(BusinessException.class)
    public BaseResponse<?> businessExceptionHandler(BusinessException e) {
        log.error("BusinessException", e);
        return ResultUtils.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public BaseResponse<?> runtimeExceptionHandler(RuntimeException e) {
        log.error("RuntimeException", e);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "系统错误");
    }

    // 全局异常拦截会捕获所有未被其他特定@ExceptionHandler方法处理的异常
    @ExceptionHandler
    public SaResult handlerException(Exception e) {
        return SaResult.error(e.getMessage());
    }
}
